<?php
declare (strict_types = 1);

namespace app\command;

use GuzzleHttp\Client;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
use think\facade\Log;

class GoodsAuthor extends Command
{
    protected function configure()
    {
        set_time_limit(0);
        //获取关联主播
        $this->getAuthor();
        //获取关联直播
        $this->getLive();

        // 指令配置
        $this->setName('sync-goods-author')
            ->setDescription('the sync-goods-author command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('sync-goods-author');
    }

    protected function getAuthor(){
        $url = 'https://www.doudouxia.com/data-center/douyin/promotion/author/ref';
        $headers = [
            'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
            'Referer' => 'https://www.doudouxia.com/data-center/douyin/promotion/author/ref',
            "Content-Type"=>"application/json"
        ];

        $client = new Client();

        //获取所有商品
        $goods = Db::name('activity_goods')->field('product_id')->group('product_id')->select();
        if($goods){
            foreach($goods as $k=>$v){
                $data = '{"product_id":'.$v['product_id'].',"page":0,"size":20}';
                $data = json_decode($data, true);
                try {
                    $response = $client->request('post', $url, ['json'=>$data, 'timeout'=>180, 'headers'=>$headers, 'verify' => false]);
                    $result = json_decode($response->getBody()->getContents(), true);
                    if($result['code'] == 1){
                        if($result['result']){
                            //清除数据
                            //Db::name('goods_author')->where(['product_id'=>$v['product_id'], 'type'=>1])->delete();

                            foreach($result['result'] as $j=>$v2){
                                $author_id = isset($v2['uid']) ? $v2['uid'] : '';
                                $data = [
                                    'nickname' => isset($v2['nickname']) ? $v2['nickname'] : '',
                                    'avatar' => isset($v2['avatar_thumb']['url_list'][0]) ? $v2['avatar_thumb']['url_list'][0] : '',
                                    'follower_count' => isset($v2['follower_count']) ? $v2['follower_count'] : 0,
                                    'zan_count' => isset($v2['total_favorited']) ? $v2['total_favorited'] : 0,
                                    'create_time' => time(),
                                    'type' => 1,
                                    'product_id' => $v['product_id'],
                                    'author_id' => $author_id,
                                    'sec_uid' => isset($v2['sec_uid']) ? $v2['sec_uid'] : '',
                                ];

                                $res = Db::name('goods_author')->where(['author_id'=>$author_id,'product_id'=>$v['product_id'], 'type'=>1])->find();

                                if(!$res){
                                    Db::name('goods_author')->insert($data);
                                }else{
                                    Db::name('goods_author')->where(['author_id'=>$author_id,'product_id'=>$v['product_id'], 'type'=>1])->update($data);
                                }
                            }
                        }
                    }
                }catch (\Exception $e){
                    Log::info('调用接口失败' . $e->getMessage());
                    exit;
                }

                echo '.';
                if($k % 100 == 0) sleep(1);
            }
        }
    }

    protected function getLive(){
        $url = 'https://www.doudouxia.com/data-center/douyin/promotion/live';
        $headers = [
            'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
            'Referer' => 'https://www.doudouxia.com/data-center/douyin/promotion/live',
            "Content-Type"=>"application/json"
        ];

        $client = new Client();

        //获取所有商品
        $goods = Db::name('activity_goods')->field('product_id')->group('product_id')->select();
        if($goods){
            foreach($goods as $k=>$v){
                $start_time = date('Y-m-d',strtotime("-1 month")) . ' 00:00:00';
                $end_time = date('Y-m-d') . ' 23:59:59';
                $data = '{"product_id":"'.$v['product_id'].'","start":"'.$start_time.'","end":"'.$end_time.'","page":0,"size":10,"sort":["create_time","desc"]}';
                $data = json_decode($data, true);
                try {
                    $response = $client->request('post', $url, ['json'=>$data, 'timeout'=>180, 'headers'=>$headers, 'verify' => false]);
                    $result = json_decode($response->getBody()->getContents(), true);
//                    echo '<pre>';print_r($result);exit;
                    if($result['code'] == 1){
                        if($result['result']['content']){
                            //清除数据
                            Db::name('goods_author')->where(['product_id'=>$v['product_id'], 'type'=>2])->delete();

                            foreach($result['result']['content'] as $j=>$v2){
                                $author_id = isset($v2['roomId']['owner_user_id']) ? $v2['roomId']['owner_user_id'] : '';
                                $data = [
                                    'nickname' => isset($v2['roomId']['title']) ? $v2['roomId']['title'] : '',
                                    'avatar' => isset($v2['roomId']['owner']['avatar_thumb']['url_list'][0]) ? $v2['roomId']['owner']['avatar_thumb']['url_list'][0] : '',
                                    'follower_count' => isset($v2['roomId']['owner']['follow_info']['follower_count']) ? $v2['roomId']['owner']['follow_info']['follower_count'] : 0,
                                    'create_time' => time(),
                                    'type' => 2,
                                    'product_id' => $v['product_id'],
                                    'author_id' => $author_id,
                                    'sec_uid' => isset($v2['roomId']['owner']['sec_uid']) ? $v2['roomId']['owner']['sec_uid'] : '',
                                    'room_avatar' => isset($v2['roomId']['cover']['url_list'][0]) ? $v2['roomId']['cover']['url_list'][0] : '',
                                    'start_time' => isset($v2['roomId']['start_time']) ? $v2['roomId']['start_time'] : 0,
                                    'finish_time' => isset($v2['roomId']['finish_time']) ? $v2['roomId']['finish_time'] : 0,
                                    'sale_num' => isset($v2['sum_order_count']) ? $v2['sum_order_count'] : 0,
                                    'sale_volume' => isset($v2['sum_sales_amount']) ? $v2['sum_sales_amount'] : 0,
                                    'user_count' => isset($v2['top_audience']) ? $v2['top_audience'] : 0,
                                    'title' => isset($v2['title']) ? $v2['title'] : 0,
                                ];

                                Db::name('goods_author')->insert($data);
                            }
                        }
                    }
                }catch (\Exception $e){
                    Log::info('调用接口失败' . $e->getMessage());
                    exit;
                }

                echo '.';
                if($k % 100 == 0) sleep(1);
            }
        }
    }
}
